/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package com.icerhe.trigger.task;

import com.icerhe.trigger.Consts;
import com.icerhe.trigger.MultiSelectPreference;
import com.icerhe.trigger.R;
import com.icerhe.trigger.TaskHelper;
import com.icerhe.trigger.TaskRingtonePreference;
import com.icerhe.trigger.R.string;
import com.icerhe.trigger.R.xml;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.provider.MediaStore;
import android.util.Log;

/**
 * @author icer
 *
 */
public class AlarmTaskSetting extends PreferenceActivity 
			implements Preference.OnPreferenceChangeListener {
	
	private CheckBoxPreference alarmEnabled;
	private EditTextPreference alarmLable;
	private EditTextPreference alarmDesc;
	private ListPreference     alarmSnooze;
	
	private MultiSelectPreference alarmMonth;
	private MultiSelectPreference alarmDayOfMonth;
	private MultiSelectPreference alarmDayOfWeek;
	private MultiSelectPreference alarmHour;
	private MultiSelectPreference alarmMinute;
	private CheckBoxPreference alarmByDow;
	
	private CheckBoxPreference useAlarmMusic;
	private Preference alarmMusic;
	private TaskRingtonePreference alarmRington;
	
	private AlarmTask task;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//TODO 是不是要像DeskClock那样重定义layout
		addPreferencesFromResource(R.xml.alarm_task_setting);
		
		
		//取得或新建Task
		long taskId = getIntent().getLongExtra(CronTask.INTENT_TASK_ID, -1);
		if (taskId==-1) {//新建任务
			task = new AlarmTask(this);
		} else {//取得已有任务
			task = (AlarmTask)TaskHelper.getCronTaskById(this, taskId);
		}
		
		//取得各preference的引用并设定setOnPreferenceChangeListener
		alarmEnabled = (CheckBoxPreference)findPreference("task_enabled");
		alarmEnabled.setOnPreferenceChangeListener(this);
		alarmLable = (EditTextPreference)findPreference("task_label");
		alarmLable.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				alarmLable.setSummary((String)arg1);
				saveTaskAsync();
				return true;
			}
		});
		alarmDesc  = (EditTextPreference)findPreference("task_description");
		alarmDesc.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				alarmDesc.setSummary((String)arg1);
				saveTaskAsync();
				return true;
			}
		});
		alarmSnooze = (ListPreference)findPreference("snooze_duration");
		alarmSnooze.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				int idx = alarmSnooze.findIndexOfValue((String)arg1);
				String selectedMode = alarmSnooze.getEntries()[idx].toString();
				alarmSnooze.setSummary(selectedMode);
				saveTaskAsync();
				return true;
			}
		});
		
		alarmMonth = (MultiSelectPreference)findPreference("task_month");
		alarmMonth.setAllCheckedSummary(getText(R.string.every_months).toString());
		alarmMonth.setOnPreferenceChangeListener(this);
		alarmDayOfMonth = (MultiSelectPreference)findPreference("task_day_of_month");
		alarmDayOfMonth.setAllCheckedSummary(getText(R.string.every_dayofmonth).toString());
		alarmDayOfMonth.setOnPreferenceChangeListener(this);
		alarmDayOfWeek = (MultiSelectPreference)findPreference("task_day_of_week");
		alarmDayOfWeek.setAllCheckedSummary(getText(R.string.every_dayofweek).toString());
		alarmDayOfWeek.setOnPreferenceChangeListener(this);
		alarmHour = (MultiSelectPreference)findPreference("task_hour");
		alarmHour.setAllCheckedSummary(getText(R.string.every_hours).toString());
		alarmHour.setOnPreferenceChangeListener(this);
		alarmMinute = (MultiSelectPreference)findPreference("task_minute");
		alarmMinute.setAllCheckedSummary(getText(R.string.every_minutes).toString());
		alarmMinute.setOnPreferenceChangeListener(this);
		alarmByDow = (CheckBoxPreference)findPreference("task_bydow");
		alarmByDow.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				Boolean val = (Boolean)arg1;
				if (val) {
					alarmDayOfWeek.setEnabled(true);
					alarmDayOfMonth.setEnabled(false);
				} else {
					alarmDayOfWeek.setEnabled(false);
					alarmDayOfMonth.setEnabled(true);
				}
				saveTaskAsync();
				return true;
			}
		});
		
		
		useAlarmMusic = (CheckBoxPreference)findPreference("use_alarm_music");
		useAlarmMusic.setOnPreferenceChangeListener(this);
		alarmRington = (TaskRingtonePreference)findPreference("alarm_ringtone");
		alarmRington.setOnPreferenceChangeListener(this);
		alarmMusic = (Preference)findPreference("alarm_music");
		alarmMusic.setOnPreferenceChangeListener(this);
		alarmMusic.setOnPreferenceClickListener(new OnPreferenceClickListener(){
			@Override
			public boolean onPreferenceClick(Preference preference) {
				Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
				intent.setType("audio/*");
				Intent destIntent = Intent.createChooser( intent, getText(R.string.select_music) );			
				startActivityForResult( destIntent, 0 );			
				return true;
			}
		});
		
		updatePreference();
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				Uri uri = data.getData();
				if( uri != null && !getRealPath(uri).equals(alarmMusic.getSummary()) ) {	
					alarmMusic.setSummary(getRealPath(uri));
					saveTask();
				}
			}
		}
	}
	
	private String getRealPath(Uri uri) {
		
		String scheme = uri.getScheme();
		
		//用Astro这样的文件管理器获取的音乐文件uri是file://path/to/file,而通过媒体播放器获取的uri是content://media/content/file_id
		if ("content".equals(scheme)) {
			String[] proj = {MediaStore.Audio.Media.DATA};
			Cursor cursor = managedQuery( uri,  
					proj, 		// Which columns to return  
		            null,       // WHERE clause; which rows to return (all rows)  
		            null,       // WHERE clause selection arguments (none)  
		            null); // Order-by clause (ascending by name) 
			int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
			cursor.moveToFirst();  
		    return cursor.getString(columnIndex); 
			
		} else {
			return uri.toString();
		}
	}

	// 用于非同步更新preference
    private static final Handler handler = new Handler();

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		saveTaskAsync();
		return true;
	}
	
	private void saveTaskAsync() {
		handler.post(new Runnable() {
			public void run() {
				saveTask();
			}
		});
	}
	
	private void updatePreference() {
		//初始化UI
		alarmEnabled.setChecked(task.isEnabled()?true:false);
		alarmLable.setText(task.title);
		alarmLable.setSummary(task.title);
		alarmDesc.setText(task.description);
		alarmDesc.setSummary(task.description);
		alarmSnooze.setValue(String.valueOf(task.getSnoozeDuration()));
		int idx = alarmSnooze.findIndexOfValue(String.valueOf(task.getSnoozeDuration()));
		alarmSnooze.setSummary(alarmSnooze.getEntries()[idx]);

		alarmMonth.setValue(task.months);
		alarmDayOfMonth.setValue(task.daysOfMonth);
		alarmDayOfWeek.setValue(task.daysOfWeek);
		alarmHour.setValue(task.hours);
		alarmMinute.setValue(task.minutes); 
		alarmByDow.setChecked(task.isByDow());
		alarmDayOfWeek.setEnabled(task.isByDow());
		alarmDayOfMonth.setEnabled(!task.isByDow());
		
		useAlarmMusic.setChecked(task.isUseMusic()); 
		String ringtonePath = task.getRingtonePath();
		if (null!=ringtonePath) alarmRington.setRingtone(Uri.parse(ringtonePath));
		alarmMusic.setSummary(task.getMusicPath());
		//alarmMusic.setEnabled(useAlarmMusic.isChecked());
	}
	
	/**
	 * 获取各preference控件的值并保存到AlarmTask对象中
	 */
	private void  saveTask() {
		Log.d(Consts.TAG, "AlarmSetting saveTask");
		task.enabled = alarmEnabled.isChecked()?1:0;
		task.title = alarmLable.getText();
		task.description = alarmDesc.getText();
		task.setSnoozeDuration(Integer.parseInt(alarmSnooze.getValue()));
		
		task.months = alarmMonth.getValue();
		task.daysOfMonth = alarmDayOfMonth.getValue();
		task.daysOfWeek = alarmDayOfWeek.getValue();
		task.hours = alarmHour.getValue();
		task.minutes = alarmMinute.getValue();
		task.setByDow(alarmByDow.isChecked());
		
		task.setUseMusic(useAlarmMusic.isChecked());
		if (null!=alarmRington.getRingtone()) task.setRingtonePath(alarmRington.getRingtone().toString());
		if (null!=alarmMusic.getSummary()) task.setMusicPath(alarmMusic.getSummary().toString());
		

		if (task.id>0) { 
			TaskHelper.updateTask(this, task);
		} else {
			int id = TaskHelper.addTask(this, task);
			task.id = id;
		}
		
	}
	
}
